package day9;

//synchronized修饰方法
//互斥锁
public class Demosynchronized {
    //普通方法
    //public void printA() {}
    public synchronized void printA() {
        String name = Thread.currentThread().getName();
        System.out.println(name + "开始执行A方法");
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(name + "结束执行A方法");
    }

    //同步方法:同一个对象的同步方法都是同步一把锁(都是当前对象this)
    public synchronized void printB() {
        String name = Thread.currentThread().getName();
        System.out.println(name + "开始执行B方法");
        try {
            Thread.sleep(500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(name + "结束执行B方法");
    }

    //静态同步方法:锁的不是this 是当前类对象(Demosynchronized.class)
    public synchronized static void printC() {

        String name = Thread.currentThread().getName();
        System.out.println(name + "开始执行C方法");
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(name + "结束执行C方法");
    }

    public synchronized static void printD() {
        String name = Thread.currentThread().getName();
        System.out.println(name + "开始执行D方法");
        try {
            Thread.sleep(300);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(name + "结束执行D方法");
    }


    public static void main(String[] args) {
        Demosynchronized d = new Demosynchronized();
        Demosynchronized d2 = new Demosynchronized();
        Demo2 dd = new Demo2();
        //A和B线程两者调用的都是同步方法，锁的是当前的this
        //他们属于同一把锁，所以A方法没有执行结束 B方法需要等待执行
        //C和D线程两者调用的静态同步方法，锁的是类对象Demosynchronized.class
        //他们也属于同一把锁，所以C方法没有执行结束 D方法需要等待执行
        new Thread(() -> {
            d.printA(); //this-->d
        }, "AAA").start();
        new Thread(() -> {
            d.printB(); //this-->d
            //dd.printB();
        }, "BBB").start();
        new Thread(() -> {
            d.printC(); //类对象->Demosynchronized.class
        }, "CCC").start();
        new Thread(() -> {
            d2.printD();//类对象->Demosynchronized.class
        }, "DDD").start();
    }
}

class Demo2 {
    public synchronized void printB() {
        String name = Thread.currentThread().getName();
        System.out.println(name + "开始执行B方法");
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(name + "结束执行B方法");
    }

}